package com.squirrel.common.service.impl;

import com.squirrel.common.domain.WebSocketServer;
import com.squirrel.common.entity.CommentarySubtitles;
import com.squirrel.common.exception.BaseException;
import com.squirrel.common.mapper.CommentarySubtitlesMapper;

import com.squirrel.common.param.danmu.SendParam;
import com.squirrel.common.response.code.CodeEnum;
import com.squirrel.common.service.CommentarySubtitlesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.squirrel.common.vo.CommentaryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * CommentarySubtitlesServiceImp 弹幕服务实现类
 * </p>
 *
 * @author 关远键
 * @since 2021/11/11 16:06
 */
@Service
public class CommentarySubtitlesServiceImp extends ServiceImpl<CommentarySubtitlesMapper, CommentarySubtitles> implements CommentarySubtitlesService {

    @Autowired
    private CommentarySubtitlesMapper subtitlesMapper;

    @Autowired
    private WebSocketServer wsServer;

    /**
     * 获取指定视频ID的所有弹幕
     *
     * @param videoId 视频ID
     * @return java.util.List<com.squirrel.common.vo.CommentaryVO>
     * @author 关远键
     * @date 2021/11/18 20:10
     */
    @Override
    public List<CommentaryVO> getAllCommentary(Integer videoId) {
        List<CommentarySubtitles> subtitles = subtitlesMapper.getByVideoId(videoId);

        if (null == subtitles) {
            throw new BaseException(CodeEnum.NON_RESOURCE);
        }

        List<CommentaryVO> list = new ArrayList<>();
        for (CommentarySubtitles subtitle : subtitles) {
            CommentaryVO vo = new CommentaryVO();
            vo.setTime(subtitle.getDmTime())
                    .setType(subtitle.getDmMode()) //不知道是什么，先填0
                    .setColor(subtitle.getDmColor())
                    .setRealTime(subtitle.getDmRealtime())
                    .setText(subtitle.getDmText());
            list.add(vo);
        }

        return list;
    }

    /**
     * 发送弹幕
     *
     * @param sendParam 弹幕参数
     * @return boolean
     * @author 关远键
     * @date 2021/11/18 20:34
     */
    @Override
    public boolean sendCommentary(SendParam sendParam) {
        wsServer.sendAllDanmu(sendParam.getId(), sendParam);

        CommentarySubtitles subtitles = new CommentarySubtitles();
        // 垃圾代码，可以优化。
        subtitles.setVideoId(sendParam.getId())
                .setDmText(sendParam.getText())
                .setDmMode(sendParam.getType())
                .setUserId(sendParam.getAuthor())
                .setDmColor(sendParam.getColor())
                .setDmTime(sendParam.getTime())
                .setDmRealtime(null).setDmPool(null).setDmFont(null);


        if (0 == subtitlesMapper.insert(subtitles)) {
            throw new BaseException(CodeEnum.DB_EXCEPTION);
        }

        return true;
    }


}
